<template>
  <div class="comment-management">
    <div class="page-header">
      <h1>评论管理</h1>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索评论内容"
          class="search-input"
          clearable
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="statusFilter" placeholder="状态筛选" clearable @change="handleSearch">
          <el-option label="已审核" :value="1" />
          <el-option label="待审核" :value="0" />
          <el-option label="已拒绝" :value="2" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
    </div>
    
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="comments"
        style="width: 100%"
        border
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="content" label="评论内容" show-overflow-tooltip />
        <el-table-column label="用户" width="120">
          <template #default="scope">
            {{ scope.row.user?.nickname || scope.row.user?.username || '未知用户' }}
          </template>
        </el-table-column>
        <el-table-column label="景点" width="150" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.attraction?.name || '未知景点' }}
          </template>
        </el-table-column>
        <!--
        <el-table-column prop="rating" label="评分" width="120">
          <template #default="scope">
            <el-rate
              v-model="scope.row.rating"
              disabled
              text-color="#ff9900"
              :max="5"
              :score-template="scope.row.rating"
            />
          </template>
        </el-table-column>
        -->
        <el-table-column prop="createdAt" label="评论时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 0"
              size="small"
              type="success"
              @click="handleApprove(scope.row)"
            >
              通过
            </el-button>
            <el-button
              v-if="scope.row.status === 0"
              size="small"
              type="danger"
              @click="handleReject(scope.row)"
            >
              拒绝
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="handleViewDetail(scope.row)"
            >
              查看
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDeleteComment(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 评论详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="评论详情"
      width="600px"
    >
      <div class="comment-detail">
        <div class="detail-item">
          <span class="label">用户：</span>
          <span>{{ currentComment.user?.nickname || currentComment.user?.username || '未知用户' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">景点：</span>
          <span>{{ currentComment.attraction?.name || '未知景点' }}</span>
        </div>
        <!--
        <div class="detail-item">
          <span class="label">评分：</span>
          <el-rate
            v-model="currentComment.rating"
            disabled
            text-color="#ff9900"
            :max="5"
          />
        </div>
        -->
        <div class="detail-item">
          <span class="label">评论时间：</span>
          <span>{{ currentComment.createdAt }}</span>
        </div>
        <div class="detail-item">
          <span class="label">评论内容：</span>
          <div class="comment-content">{{ currentComment.content }}</div>
        </div>
        <div class="detail-item" v-if="currentComment.images && currentComment.images.length > 0">
          <span class="label">评论图片：</span>
          <div class="comment-images">
            <img
              v-for="(image, index) in currentComment.images"
              :key="index"
              :src="image"
              :alt="`评论图片 ${index + 1}`"
              class="comment-image"
              @click="previewImage(image)"
            />
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button v-if="currentComment.status === 0" type="success" @click="handleApprove(currentComment)">
            通过
          </el-button>
          <el-button v-if="currentComment.status === 0" type="danger" @click="handleReject(currentComment)">
            拒绝
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 图片预览对话框 -->
    <el-dialog v-model="imagePreviewVisible" width="800px">
      <img :src="previewImageUrl" style="width: 100%;" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import api from '@/api/auth';

// 搜索查询
const searchQuery = ref('');
const statusFilter = ref('');

// 表格数据
const comments = ref([]);
const loading = ref(false);

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框
const dialogVisible = ref(false);
const currentComment = reactive({
  commentId: '',
  content: '',
  user: {
    username: '',
    nickname: ''
  },
  attraction: {
    name: ''
  },
  rating: 0,
  createdAt: '',
  status: 0,
  images: []
});

// 图片预览
const imagePreviewVisible = ref(false);
const previewImageUrl = ref('');

// 获取评论列表
const fetchComments = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchQuery.value || undefined,
      status: statusFilter.value !== '' ? statusFilter.value : undefined
    };
    
    // 调用API获取评论列表，使用新的接口
    const response = await api.get('/comment/list', { params });
    if (response.code === 200 && response.data) {
      // 从响应中提取评论列表和总数
      comments.value = response.data.list || [];
      total.value = response.data.total || 0;
      
      // 处理评论数据，确保所有需要的字段都存在
      comments.value.forEach(comment => {
        // 确保评分字段存在，如果为null则设置为0
        if (comment.rating === null || comment.rating === undefined) {
          comment.rating = 0;
        }
        
        // 确保图片数组存在
        if (!comment.images) {
          comment.images = [];
        }
        
        // 确保用户和景点信息存在
        if (!comment.user) {
          comment.user = { nickname: '未知用户', username: '未知用户' };
        }
        
        if (!comment.attraction) {
          comment.attraction = { name: '未知景点' };
        }
      });
    } else {
      ElMessage.error(response.data?.message || '获取评论列表失败');
    }
  } catch (error) {
    console.error('获取评论列表失败:', error);
    ElMessage.error('获取评论列表失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 查看评论详情
const handleViewDetail = (row) => {
  Object.assign(currentComment, row);
  dialogVisible.value = true;
};

// 预览图片
const previewImage = (url) => {
  previewImageUrl.value = url;
  imagePreviewVisible.value = true;
};

// 搜索评论
const handleSearch = () => {
  currentPage.value = 1;
  fetchComments();
};

// 通过评论
const handleApprove = async (comment) => {
  try {
    const response = await api.post(`/comment/admin/updateStatus/${comment.commentId}/1`);
    
    if (response.code === 200) {
      ElMessage.success('评论已通过审核');
      // 更新本地评论状态
      comment.status = 1;
    } else {
      ElMessage.error(response.message || '操作失败');
    }
  } catch (error) {
    console.error('通过评论失败:', error);
    ElMessage.error('操作失败，请稍后再试');
  }
};

// 拒绝评论
const handleReject = async (comment) => {
  try {
    const response = await api.post(`/comment/admin/updateStatus/${comment.commentId}/2`);
    
    if (response.code === 200) {
      ElMessage.success('评论已拒绝');
      // 更新本地评论状态
      comment.status = 2;
    } else {
      ElMessage.error(response.message || '操作失败');
    }
  } catch (error) {
    console.error('拒绝评论失败:', error);
    ElMessage.error('操作失败，请稍后再试');
  }
};

// 删除评论
const handleDeleteComment = (row) => {
  ElMessageBox.confirm(
    `确定要删除用户 "${row.user?.nickname || row.user?.username || '未知用户'}" 对 "${row.attraction?.name || '未知景点'}" 的评论吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const response = await api.post(`/comment/admin/deleteComment/${row.commentId}`);
        
        if (response.data && response.data.code === 200) {
          ElMessage.success('删除评论成功');
          fetchComments();
        } else {
          ElMessage.error(response.data?.message || '删除评论失败');
        }
      } catch (error) {
        console.error('删除评论失败:', error);
        ElMessage.error('删除评论失败，请稍后再试');
      }
    })
    .catch(() => {
      // 用户取消操作
    });
};

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 1:
      return 'success';
    case 0:
      return 'warning';
    case 2:
      return 'danger';
    case 3:
      return 'info';
    default:
      return 'info';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1:
      return '已审核';
    case 0:
      return '待审核';
    case 2:
      return '已拒绝';
    case 3:
      return '已隐藏';
    default:
      return '未知';
  }
};

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchComments();
};

// 页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchComments();
};

onMounted(() => {
  fetchComments();
});
</script>

<style scoped>
.comment-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.comment-detail {
  padding: 10px;
}

.detail-item {
  margin-bottom: 15px;
}

.label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}

.comment-content {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  margin-top: 5px;
  white-space: pre-wrap;
}

.comment-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 5px;
}

.comment-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    flex-wrap: wrap;
  }
  
  .search-input {
    flex: 1;
  }
}
</style>